//
//  JKeepRecordController.m
//  HeadIndustry
//
//  Created by jun on 2017/9/21.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JKeepRecordController.h"
#import <CoreLocation/CoreLocation.h>
#import <QBImagePickerController/QBImagePickerController.h>

#import "JSelImgView.h"
@interface JKeepRecordController ()<CLLocationManagerDelegate,QBImagePickerControllerDelegate ,UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic,strong) CLLocationManager *manager;
@property (nonatomic, assign) CGFloat  minY;

@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UIButton *locationBtn;

@property (nonatomic, strong) NSMutableArray *selImgArr;
@property (nonatomic, strong) NSMutableArray *selImgBtnArr;
@property (nonatomic, assign) NSInteger  selBtnTag;
@property (nonatomic, assign) NSInteger  selImgNum;

@property (nonatomic, copy) NSMutableDictionary *paramerDic ;

@end

@implementation JKeepRecordController

- (NSMutableDictionary *)paramerDic
{
    if (_paramerDic == nil) {
        _paramerDic = [NSMutableDictionary dictionary];
        [_paramerDic setObject:@(0) forKey:@"LogImg"];
        [_paramerDic setObject:@([GLOBALDATA userInfoModel].CustomerId) forKey:@"UserId"];
        [_paramerDic setObject:@([GLOBALDATA userInfoModel].CustomerId) forKey:@"CreatorId"];
    }
    
//    "Content": ""，     //内容
//    "Address": ""，
//    "PIC":[{ //图片必填
//    MimeType:"image/jpeg", /固定值
//    SeoFilename:"", //固定值为空
//    TitleAttribute:"" //base64的内容
//    }]
//    LogImg：0 //固定值
    
    return _paramerDic;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [super InitUI];
    self.titleLabel.text = @"写日记";
    self.leftButton.hidden = NO;
    [self.leftButton setImage:[UIImage imageNamed:backBtnImg] forState:UIControlStateNormal];
    self.leftButton.frame = CGRectMake(8, self.leftButton.frame.origin.y, 30, 30);
    self.rightButton.hidden = NO;
    [self.rightButton setTitle:@"发送" forState:UIControlStateNormal];
    self.rightButton.layer.borderColor = kRGBColor(150, 150, 150).CGColor;
    self.rightButton.layer.cornerRadius = 3;
    self.rightButton.layer.borderWidth = 0.5;
    
    _selImgBtnArr = [NSMutableArray array];
    _selImgArr = [NSMutableArray array];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kWindowW, self.contentView.height)];
    _scrollView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:_scrollView];
    
    [self setConfigBgView];
    [self setUpLocation];
}

- (void)setConfigBgView
{
    UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(10,10,kWindowW - 20, 200)];
//    textView.backgroundColor = UIColorFromHex(0xe6ebf5);
    textView.font = [UIFont systemFontOfSize:14];
    [_scrollView addSubview:textView];
    _textView = textView;
    
    UILabel *placeHolderLabel = [[UILabel alloc] init];
    placeHolderLabel.text = @"分享你的美";
    placeHolderLabel.numberOfLines = 0;
    placeHolderLabel.textColor = kCOLOR_HEX(0x8a8a99);
    [placeHolderLabel sizeToFit];
    [textView addSubview:placeHolderLabel];
    
    // same font
    textView.font = [UIFont systemFontOfSize:14];
    placeHolderLabel.font = [UIFont systemFontOfSize:14];
    
    [textView setValue:placeHolderLabel forKey:@"_placeholderLabel"];

    UIButton *submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    submitBtn.frame = CGRectMake(10, textView.bottom +10 , kWindowW - 20, 20);
//    submitBtn.backgroundColor = kRGBColor(245, 245, 245);
    [submitBtn setImage:[UIImage imageNamed:@"adressnine_1"] forState:UIControlStateNormal];
    [submitBtn setTitleColor:kRGBColor(150, 150, 150) forState:UIControlStateNormal];
    [submitBtn setTitle:@" 你在哪里" forState:UIControlStateNormal];
    submitBtn.titleLabel.font = kFONT_TITLE(16);
    submitBtn.layer.cornerRadius = 5;
    [submitBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, submitBtn.width - 20)];
    [submitBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, submitBtn.width - 90)];
    [submitBtn addTarget:self action:@selector(submitBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:submitBtn];
    _locationBtn = submitBtn;
    
    
    YYLabel *textLabel1 = [YYLabel new];
    textLabel1.frame = CGRectMake(10, submitBtn.bottom, 70, 50);
    textLabel1.text = @"上传图片";
    textLabel1.font = kFONT_TITLE(16);
    [_scrollView addSubview:textLabel1];
    
    YYLabel *textLabel2 = [YYLabel new];
    textLabel2.frame = CGRectMake(textLabel1.right, submitBtn.bottom, kWindowW - textLabel1.right - 10, 50);
    textLabel2.text = @"(最多可以上传9张图片)";
    textLabel2.font = kFONT_TITLE(16);
    textLabel2.textColor = kRGBColor(150, 150, 150);
    [_scrollView addSubview:textLabel2];
    
    _minY = textLabel2.bottom;
    [self setConfigSelImgBtn:_minY];
}

- (void)setUpLocation
{
    if ([CLLocationManager locationServicesEnabled]) {
        
        _manager = [[CLLocationManager alloc] init];
        _manager.delegate = self;
        _manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        _manager.distanceFilter  = kCLDistanceFilterNone;
//        [_manager startUpdatingLocation];  // 开始定位
        //        [_manager startUpdatingHeading];  // 开始更新方向
        
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"无法进行定位", comment:@"无法进行定位") message:NSLocalizedString(@"请检查您的设备是否开启定位功能", comment:@"请检查您的设备是否开启定位功能") delegate:self cancelButtonTitle:NSLocalizedString(@"确定",comment:@"确定") otherButtonTitles:nil, nil];
        [alert show];
    }
    // 实例化对象
    _manager = [[CLLocationManager alloc] init];
    
    _manager.delegate = self;
    
    // 请求授权，记得修改的infoplist，NSLocationAlwaysUsageDescription（描述）
    [_manager requestWhenInUseAuthorization];
    
    //    [_manager stopUpdatingLocation];
//    [_manager startUpdatingLocation];
    
}

#pragma mark - 代理方法，当授权改变时调用
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    
    // 获取授权后，通过
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        
        //开始定位(具体位置要通过代理获得)
//        [_manager startUpdatingLocation];
        
        //设置精确度
        _manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        
        //设置过滤距离
        _manager.distanceFilter = 1000;
        
        //开始定位方向
        //        [_manager startUpdatingHeading];
    }
    
    
}

#pragma mark - 定位代理
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    //    NSLog(@"%@",locations);
    
    //获取当前位置
    CLLocation *location = manager.location;
    //获取坐标
    //    CLLocationCoordinate2D corrdinate = location.coordinate;
    
    //打印地址
    //    NSLog(@"latitude = %f longtude = %f",corrdinate.latitude,corrdinate.longitude);
    
    // 地址的编码通过经纬度得到具体的地址
    CLGeocoder *gecoder = [[CLGeocoder alloc] init];
    
    [gecoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        
        CLPlacemark *placemark = [placemarks firstObject];
        
        
        
        if (placemark != nil) {
            
            NSArray* addrArray = [placemark.addressDictionary objectForKey:@"FormattedAddressLines"];
            
            //将详细地址拼接成一个字符串
            
            NSMutableString* addr = [[NSMutableString alloc] init];
            
            for(int i =0; i < addrArray.count ; i ++){
                
                [addr appendString:addrArray[i]];
                
            }
            
            
             NSLog(@"======%@",addr);
            [_locationBtn setTitle:addr forState:UIControlStateNormal];
            [_locationBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -45, 0, 0)];
        }
        
    }];

    //停止定位
    [_manager stopUpdatingLocation];
    
}

- (void)setConfigSelImgBtn:(CGFloat)minY
{
    CGFloat width = kWindowW/3.0;
    _selBtnTag = 0;
    
    for (int i = 0; i < 9; i++) {
        JSelImgView *btn = [[JSelImgView alloc]initWithFrame:CGRectMake(( i % 3 ) * width, minY + 10 + (i / 3) * width, width, width) tag:i];
        [self.scrollView addSubview:btn];
        btn.tag = i;
        btn.isBigImg = NO;
        [self.selImgBtnArr addObject:btn];
        
        if (i > 0) {
            btn.hidden = YES;
        }
        
        btn.delImgBtnBlock = ^(NSInteger tag) {
            
            JSelImgView *view = self.selImgBtnArr[i];
            if (view.isBigImg == NO) {
                return ;
            }
            
            [self.selImgArr removeObjectAtIndex:tag];
            
            for (int i = 0; i< self.selImgArr.count; i++) {
                JSelImgView *btn = self.selImgBtnArr[i];
                [btn.imgbtn setImage:self.selImgArr[i] forState:UIControlStateNormal];
            }
            
            _selImgNum -= 1;
            
            if (_selImgNum == 8)
            {
                JSelImgView *btn = self.selImgBtnArr[_selImgNum];
                [btn.imgbtn setImage:[UIImage imageNamed:@"gophone_icon"] forState:UIControlStateNormal];
                btn.isBigImg = NO;
            }
            else  {
                JSelImgView *btn = self.selImgBtnArr[_selImgNum+1];
                btn.isBigImg = NO;
                btn.hidden = YES;
                
                JSelImgView *btn2 = self.selImgBtnArr[_selImgNum];
                [btn2.imgbtn setImage:[UIImage imageNamed:@"gophone_icon"] forState:UIControlStateNormal];
                btn2.isBigImg = NO;
            }
            
            _scrollView.contentSize = CGSizeMake(kWindowW, (self.selImgArr.count / 3 + 1) * (kWindowW/3.0) + 40 + _minY);
        };
        
        btn.addImgBtnBlock = ^(NSInteger tag) {
            JSelImgView *view = self.selImgBtnArr[tag];
            
            if (view.isBigImg == NO) {
                [self setImagePickerBtn:tag];
            }
            else
            {
                NSLog(@"放大");
            }
            
        };
    }
}

- (void)setImagePickerBtn:(NSInteger)tag
{
    _selBtnTag = tag;
    
    UIAlertController *sheetController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *xiangji = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self xiangjiMethod:tag];
    }];
    
    UIAlertAction *xiangce = [UIAlertAction actionWithTitle:@"手机相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self xiangceMethod:tag];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [sheetController addAction:xiangji];
    [sheetController addAction:xiangce];
    [sheetController addAction:cancel];
    
    [self presentViewController:sheetController animated:YES completion:nil];
    
}

- (void)xiangjiMethod:(NSInteger)tag {
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]){
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        //        self.imagePC = imagePickerController;
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;//no
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickerController.showsCameraControls  = YES;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }else{
        
        //        jHUDNormal(@"您的设备不支持照相功能!")
    }
}

//#pragma mark  imagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    //
//    CGFloat width = kWindowW/3.0;
//    NSData *imgData = [self resetSizeOfImageData:image maxSize:width];
//    image = [UIImage imageWithData:imgData];
    
    JSelImgView *view = self.selImgBtnArr[_selBtnTag];
    [view.imgbtn setImage:image forState:UIControlStateNormal];
    view.isBigImg = YES;
    [self.selImgArr addObject:image];
    
    _selImgNum = view.tag +1;
    
    if (_selBtnTag < 9) {
        JSelImgView *view2 = self.selImgBtnArr[_selBtnTag+1];
        view2.hidden = NO;
    }
    
    _scrollView.contentSize = CGSizeMake(kWindowW, (self.selImgArr.count / 3 + 1) * (kWindowW/3.0) + 410 + _minY);
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)xiangceMethod:(NSInteger)tag {
    QBImagePickerController *imagePickerController =[QBImagePickerController new];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.mediaType = QBImagePickerMediaTypeImage;//图片
    
    imagePickerController.showsNumberOfSelectedAssets = YES;//在界面下方显示已经选择图像的数量
    
    imagePickerController.maximumNumberOfSelection = 9 - _selImgNum;
    imagePickerController.prompt = [NSString stringWithFormat:@"请选择图片，最多%ld张",9 - _selImgNum];
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

//1.获取到图像
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {
    
    for (int i = 0; i< assets.count; i++) {
        PHAsset * asset = assets[i];
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        // 同步获得图片, 只会返回1张图片
        options.synchronous = YES;
        
        // 是否要原图
        CGSize size = /* DISABLES CODE */ (YES) ? CGSizeMake(asset.pixelWidth, asset.pixelHeight) : CGSizeZero;
        
        // 从asset中获得图片
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            
//            CGFloat width = kWindowW/3.0;
//            NSData *imgData = [self resetSizeOfImageData:result maxSize:width];
//            result = [UIImage imageWithData:imgData];
            
            [self.selImgArr addObject:result];
            
            JSelImgView *view = self.selImgBtnArr[_selBtnTag+i];
            [view.imgbtn setImage:result forState:UIControlStateNormal];
            view.isBigImg = YES;
            view.hidden = NO;
            _selImgNum += 1;
            
            if (_selImgNum < 9) {
                JSelImgView *view = self.selImgBtnArr[_selImgNum];
                view.isBigImg = NO;
                view.hidden = NO;
            }
            
        }];
        
        
    }
    _scrollView.contentSize = CGSizeMake(kWindowW, (self.selImgArr.count / 3 + 1) * (kWindowW/3.0) + 40 + _minY);
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
//2.取消获取图像
- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    //do something
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)submitBtnClick:(UIButton *)rightButton
{
    [_manager startUpdatingLocation];  // 开始定位
}

- (void)rightButtonClick:(UIButton *)rightButton
{
    
//    if ([self requestBody] == NO) return;
    
    if (_textView.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"分享内容不能为空"];
        return ;
    }
    NSString *str = _locationBtn.titleLabel.text;
    if ([str isEqualToString:@" 你在哪里"]) {
        [SVProgressHUD showErrorWithStatus:@"分享位置不能为空"];
        return ;
    }
    
    if (self.selImgArr.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"至少添加一张图片"];
        return ;
    }
    
    [self.paramerDic setObject:_textView.text forKey:@"Content"];
    [self.paramerDic setObject:_locationBtn.titleLabel.text forKey:@"Address"];
    NSMutableArray *picArr = [NSMutableArray array];
    
    rightButton.enabled = NO;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (UIImage *img in self.selImgArr) {
            
            NSData *data = [self resetSizeOfImageData:img maxSize:0.5];
            NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
            
            
            NSDictionary *dic = @{@"MimeType":@"image/jpeg",
                                  @"SeoFilename":@"",
                                  @"TitleAttribute":encodedImageStr};

            
            [picArr addObject:dic];
        }
        
        [self.paramerDic setObject:picArr forKey:@"PIC"];
        
        NSDictionary *dic = self.paramerDic;
        
        [SVProgressHUD showWithStatus:@"创建中。。。"];
        
        NSString *url = @"TimeShow/AddTimeShow";
        [JNetManager subBeautifulSocialHubRequedtUrl:url
                                              dicPar:dic
                                             success:^(id response) {
                                                 if ([response integerValue] == 1) {
                                                     [SVProgressHUD showSuccessWithStatus:@"创建成功"];
                                                     [self.navigationController popViewControllerAnimated:YES];
                                                 }
                                             } failure:^(NSString *err) {
                                                 rightButton.enabled = YES;
                                                 [SVProgressHUD showErrorWithStatus:err];
                                             }];
        
    });
    
    
}

- (BOOL)requestBody {
    
    
    
    
    return YES;
}

- (void)leftButtonClick:(UIButton *)leftButton
{
    [super leftButtonClick:leftButton];
    [self.navigationController popViewControllerAnimated:YES];
}

// 压缩图片
- (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize
{
    //先调整分辨率
    CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);
    
    CGFloat tempHeight = newSize.height / 1024;
    CGFloat tempWidth = newSize.width / 1024;
    
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);
    }
    else if (tempHeight > 1.0 && tempWidth < tempHeight){
        newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);
    }
    
    UIGraphicsBeginImageContext(newSize);
    [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //调整大小
    NSData *imageData;
    if (UIImagePNGRepresentation(newImage)) {
        imageData = UIImagePNGRepresentation(newImage);
    }else{
        imageData = UIImageJPEGRepresentation(newImage, 0.5);
    }
    
    NSUInteger sizeOrigin = [imageData length];
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    if (sizeOriginKB > maxSize) {
        NSData *finallImageData = UIImageJPEGRepresentation(newImage,0.20);
        return finallImageData;
    }
    
    return imageData;
}


/**
 * 图片压缩到指定大小
 * @param targetSize 目标图片的大小
 * @param sourceImage 源图片
 * @return 目标图片
 */
- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize withSourceImage:(UIImage *)sourceImage
{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    
    return newImage;
}


- (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
            } else if (data.length > maxLength) {
                max = compression;
                } else {
                    break;
                    }
        }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)), (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
        }
    
    return resultImage;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.contentView endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSString *)convertToJsonData:(NSDictionary *)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
